//
//  AppDelegate.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/6/26.
//  Copyright (c) 2015年 HeiMa. All rights reserved.
//

import UIKit
import AFNetworking
var shareAccount = UserAccount.loadAccount()
var HMSwitchRootVCNotification = "HMSwitchRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        print(shareAccount)
        
        setupAppearance()
        setupNetwork()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: HMSwitchRootVCNotification, object: nil)
        return true
    }
    
    private func setupNetwork(){
        // 设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)

    }
    
    func switchViewController(n : NSNotification) {
        let isMainVC = n.object as! Bool
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
    }
    
    private func defaultViewController() ->UIViewController {
        if shareAccount != nil {
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
    
    private func isNewUpdate() -> Bool {
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
//        let version = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        let version = Double(currentVersion)!
        print(version)
        
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        print(sandBoxVersion)
        
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
    }


    private func setupAppearance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
}

